package com.ztesoft.book.admin.filter;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lzq.
 * @description Xss过滤帮助类
 * @date 2021-07-26 17:29
 */
public final class XssFilterUtil {
    private static List<Pattern> patterns = null;

    public static final String TOKEN = "token";

    private XssFilterUtil() {

    }

    private static List<Object[]> getXssPatternList() {
        List<Object[]> ret = new ArrayList<>();

        ret.add(new Object[]{"<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"<(no)?marquee[^>]*>.*?</(no)?marquee>", Pattern.CASE_INSENSITIVE});

        ret.add(new Object[]{"</script>", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        return ret;
    }

    private static List<Pattern> getPatterns() {

        if (patterns == null) {

            List<Pattern> list = new ArrayList<>();

            String regex;
            Integer flag;
            int arrLength;

            for (Object[] arr : getXssPatternList()) {
                arrLength = arr.length;
                for (int i = 0; i < arrLength; i++) {
                    regex = (String) arr[0];
                    flag = (Integer) arr[1];
                    list.add(Pattern.compile(regex, flag));
                }
            }

            patterns = list;
        }

        return patterns;
    }

    /**
     * json替换会出现问题
     * 例子：{"curriculumVitae":" class=\"media-wrap image-wrap\" "}
     * 所以需要保留\".
     *
     * @param value value
     *
     * @return String
     */
    public static String stripXss(String value) {
        Matcher matcher;

        String unUrl = value;
        //单独处理< >
        String tempPattern = "\\\\u003c";
        Pattern r = Pattern.compile(tempPattern);
        matcher = r.matcher(unUrl);
        if (matcher.find()) {
            unUrl = matcher.replaceAll("<");
        }

        tempPattern = "\\\\u003e";
        r = Pattern.compile(tempPattern);
        matcher = r.matcher(unUrl);
        if (matcher.find()) {
            unUrl = matcher.replaceAll(">");
        }


        if (StringUtils.isNotBlank(unUrl)) {
            for (Pattern pattern : getPatterns()) {


                matcher = pattern.matcher(unUrl);
                // 匹配
                if (matcher.find()) {
                    // 删除相关字符串
                    unUrl = matcher.replaceAll("");
                }
            }


        }

        return unUrl;
    }
}
